package top.infopub.mgc.wsImpl;


import java.io.File;
import java.io.FileInputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import top.infopub.common.ErrorCodeEnum;
import top.infopub.dubbo.vo.mgc.TemplateBuildVo;
import top.infopub.dubbo.ws.mgc.TemplateBuildService;
import top.infopub.mgc.core.domain.TemplateInfo;
import top.infopub.mgc.core.service.MsgTemplateService;
import top.infopub.mgc.util.PdfUtils;
import top.infopub.vo.ResponseVo;


/**
 * 模板构建生成html/pdf ws接口
 * @author Awoke
 * @version 2018年9月20日
 * @see WsQuartzJobServiceImpl
 * @since
 */
@Service
public class WsTemplateBuildServiceImpl implements TemplateBuildService {

    private final static Logger logger = LoggerFactory.getLogger(WsTemplateBuildServiceImpl.class);

    @Autowired
    private MsgTemplateService msgTemplateService;

    @SuppressWarnings("unchecked")
    @Override
    public ResponseVo<String> generatorHtml(TemplateBuildVo toBuildVo) {
        if (toBuildVo == null || StringUtils.isBlank(toBuildVo.getTemplateId())) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getResponseVo();
        }
        TemplateInfo info = msgTemplateService.selectTemplateInfoById(toBuildVo.getTemplateId());
        if (info == null) {
            return ErrorCodeEnum.ERROR_MGC_TEMPLATE.getResponseVo();
        }
        try {
            // 使用 FreeMarkerTemplateUtils 生成html 
            String htmlContent = FreeMarkerTemplateUtils.processTemplateIntoString(
                info.getTemplateObj(), toBuildVo.getCtxParamMap());
            if (!StringUtils.isEmpty(htmlContent)) {
                return new ResponseVo<String>(htmlContent);
            }
            else {
                return ErrorCodeEnum.ERROR_MGC_TEMPLATE_GEN_HTML.getResponseVo();
            }
        }
        catch (Exception e) {
            logger.error("generatorHtml error " + toBuildVo, e);
            return ErrorCodeEnum.ERROR_MGC_TEMPLATE_GEN_HTML.getResponseVo(e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseVo<String> generatorPdf(TemplateBuildVo toBuildVo, String pdfPath) {
        if (toBuildVo == null || StringUtils.isBlank(toBuildVo.getTemplateId())
            || StringUtils.isBlank(pdfPath)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getResponseVo();
        }
        if (new File(pdfPath).exists()) {
            logger.info("pdf: {} Already Exists", pdfPath);
            return ResponseVo.getSuccessResponse(pdfPath);
        }
        TemplateInfo info = msgTemplateService.selectTemplateInfoById(toBuildVo.getTemplateId());
        if (info == null) {
            return ErrorCodeEnum.ERROR_MGC_TEMPLATE.getResponseVo();
        }
        boolean isSuccess = false;
        try {
            // 使用 FreeMarkerTemplateUtils 生成html 
            String htmlContent = FreeMarkerTemplateUtils.processTemplateIntoString(
                info.getTemplateObj(), toBuildVo.getCtxParamMap());
            if (!StringUtils.isEmpty(htmlContent)) {
                // 生成pdf
                if (PdfUtils.generateToFile(htmlContent, pdfPath)) {
                    isSuccess = true;
                    return ResponseVo.getSuccessResponse(pdfPath);
                }
            }
            return ErrorCodeEnum.ERROR_MGC_TEMPLATE_GEN_PDF.getResponseVo();
        }
        catch (Exception e) {
            logger.error("generatorPdf error " + toBuildVo + ", pdfPath=" + pdfPath, e);
            return ErrorCodeEnum.ERROR_MGC_TEMPLATE_GEN_PDF.getResponseVo();
        }
        finally {
            if (!isSuccess && new File(pdfPath).exists()) {
                new File(pdfPath).delete();
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseVo<byte[]> pdfFileStream(String pdfPath) {
        if (!new File(pdfPath).exists()) {
            logger.warn("获得pdf文件流异常，{} 文件不存在~", pdfPath);
            return ErrorCodeEnum.ERROR_MGC_PDF_NO_EXIST.getResponseVo();
        }
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(pdfPath);
            int size = fis.available();
            byte[] buffer = new byte[size];
            IOUtils.read(fis, buffer);
            return ResponseVo.getSuccessResponse(buffer);
        }
        catch (Exception e) {
            logger.error("pdfFileStream error, pdfPath=" + pdfPath, e);
            return ErrorCodeEnum.ERROR_MGC_PDF_STREAM.getResponseVo();
        }
        finally {
            IOUtils.closeQuietly(fis);
        }
    }

}
